import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmfbase/BaiduMap/bmfmap_base.dart';
import 'package:flutter_bmfbase/BaiduMap/map/bmf_models.dart';
import 'package:flutter_bmfbase/BaiduMap/map/bmf_types.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_android_option.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_ios_option.dart';
import 'package:flutter_bmfmap/BaiduMap/bmfmap_map.dart';

class AddAdress extends StatefulWidget {
  @override
  AddAdressState createState() => new AddAdressState();

}
void main() {
  runApp(new MaterialApp(home: AddAdress()));
}
List Mycoordinate = new List(2);
BMFMapController myMapController;
double latitude;
double longitude;
String username = '小明';
String PhoneNumber = '15688888888';
String AdressDet = '';
TextEditingController AddDetailController = new TextEditingController();
TextEditingController Usercontroller = new TextEditingController();
TextEditingController Phonecontroller = new TextEditingController();
BMFCoordinate coordinate = BMFCoordinate(Mycoordinate[0], Mycoordinate[1]);
BMFMapOptions initMapOptions() {
  BMFMapOptions mapOptions = BMFMapOptions(
      center:BMFCoordinate(Mycoordinate[0], Mycoordinate[1]),
      zoomLevel: 16,
      mapPadding: BMFEdgeInsets(left: 0, top: 0, right: 0, bottom: 0));
  return mapOptions;
}
class AddAdressState extends State<AddAdress> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
          backgroundColor: Color.fromRGBO(51, 51, 51, 1),
          titleSpacing: 0.0,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              FlatButton(
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                child: Row(
                  children: [
                    Icon(
                      Icons.arrow_back_ios,
                      color: Colors.white,
                    ),
                    Text(
                      '返回',
                      style: TextStyle(color: Colors.white, fontSize: 16),
                    )
                  ],
                ),
                onPressed: () {},
              ),
              Container(
                child: Row(
                  children: [
                    Text(
                      '新增地址',
                      style: TextStyle(fontSize: 16),
                    ),
                    SizedBox(
                      width: 25,
                    )
                  ],
                ),
              ),
              IconButton(icon: Icon(Icons.more_horiz), onPressed: () {})
            ],
          )),
      body: AdressHomePage(),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    Usercontroller = TextEditingController.fromValue(
      TextEditingValue(
          text: '小明',
          selection: TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream,
              offset: Usercontroller.text.length))),
    );
    Phonecontroller = TextEditingController.fromValue(
      TextEditingValue(
          text: PhoneNumber,
          selection: TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream,
              offset: Usercontroller.text.length))),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}

class AdressHomePage extends StatefulWidget {
  @override
  AdressHomePageState createState() => new AdressHomePageState();

}

class AdressHomePageState extends State<AdressHomePage> {
  @override
  String errorText;
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          //用户名
          Row(
            children: [
              Text(
                '姓名:',
                style: TextStyle(letterSpacing: 30),
              ),
              //获取用户名
              Container(
                height: 30,
                width: MediaQuery
                    .of(context)
                    .size
                    .width * 0.6,
                child: TextField(
                  controller: Usercontroller,
                  onChanged: (value) {
                    username = value;
                    print('用户名：' + Usercontroller.text);
                  },
                  decoration: InputDecoration(
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.black,
                        ),
                      )),
                ),
              ),
            ],
          ),

          SizedBox(
            height: 20,
          ),

          //联系电话
          Row(
            children: [
              Padding(
                padding: EdgeInsets.only(left: 10),
                child: Text(
                  '联系电话:',
                  style: TextStyle(letterSpacing: 10),
                ),
              ),

              //获取联系电话
              Container(
                height: 30,
                width: MediaQuery
                    .of(context)
                    .size
                    .width * 0.6,
                child: TextField(
                  controller: Phonecontroller,
                  onChanged: (value) {
                    setState(() {
                      if (!isChinaPhoneLegal(Phonecontroller.text)) {
                        errorText = '电话号码都不会输入？就这？';
                      } else {
                        errorText = null;
                      }
                    });
                    PhoneNumber = value;
                    print('联系电话：' + Phonecontroller.text);
                  },
                  decoration: InputDecoration(
                    errorText: getError(),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.black,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),

          Row(
            children: [
              Padding(
                padding: EdgeInsets.only(left: 10),
                child: Text(
                  '选择地址:',
                  style: TextStyle(letterSpacing: 10),
                ),
              ),
              Container(
                width: 80,
                height: 50,
                child: DropdownButton(
                    isExpanded: true, //箭头到边上去
                    value: '省',
                    items: [
                      DropdownMenuItem(
                        child: Text('省'),
                        value: '省',
                      ),
                    ],
                    onChanged: (value) {}),
              ),
              Container(
                width: 80,
                height: 50,
                child: DropdownButton(
                    isExpanded: true, //箭头到边上去
                    value: '市',
                    items: [
                      DropdownMenuItem(
                        child: Text('市'),
                        value: '市',
                      ),
                    ],
                    onChanged: (value) {}),
              ),
              Container(
                width: 80,
                height: 50,
                child: DropdownButton(
                    isExpanded: true, //箭头到边上去
                    value: '区',
                    items: [
                      DropdownMenuItem(
                        child: Text('区'),
                        value: '区',
                      )
                    ],
                    onChanged: (value) {}),
              ),
            ],
          ),

          Row(
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 10),
                  child: Text(
                    '详细地址:',
                    style: TextStyle(letterSpacing: 10),
                  ),
                ),

                //详细地址框框
                Expanded(
                  child: Container(
                    height: MediaQuery
                        .of(context)
                        .size
                        .height * 0.1,
                    width: MediaQuery
                        .of(context)
                        .size
                        .width * 0.6,
                    child: TextField(
                      maxLines: 2,
                      controller: AddDetailController,
                      decoration: InputDecoration(
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.black,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),

              ]),

          //定位
          Row(
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 10),
                  child: Text(
                    '定位:',
                    style: TextStyle(letterSpacing: 10),
                  ),
                ),

                //详细地址
                Container(
                  height: 30,
                  width: MediaQuery
                      .of(context)
                      .size
                      .width * 0.55,
                  child: TextField(
                    decoration: InputDecoration(
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.black,
                        ),
                      ),
                    ),
                  ),
                ),

                GestureDetector(
                  onTap: () {
                    AddDetailController.text = AdressDet;
                  },
                  child: Container(
                    width: 50,
                    height: 30,
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(left: 20, top: 10),
                    child: Text('定位'),
                    decoration: BoxDecoration(
                        border: Border.all(width: 1),
                        borderRadius: BorderRadius.circular(5)
                    ),
                  ),
                ),
              ]),
          //提示小字
          Container(
            margin: EdgeInsets.only(left: 0),
            child: Text('如果输入地址后无法定位，请在地图上直接点击选择地点。',
              style: TextStyle(color: Colors.grey, fontSize: 13),),
          ),

          Container(
            child: Text(''),
          ),

          generateMap(Mycoordinate),



        ],
      ),
    );
  }


  @override
  void initState() {
    LocationFlutterPlugin locationPlugin = new LocationFlutterPlugin();
//BMF初始设置
    BaiduLocationAndroidOption androidOption = new BaiduLocationAndroidOption();
    androidOption.setCoorType("bd09ll"); // 设置返回的位置坐标系类型
    androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
    androidOption.setIsNeedAddres(true); // 设置是否需要返回地址信息
    androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
    androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
    androidOption.setOpenGps(true); // 设置是否需要使用gps
    androidOption.setLocationMode(LocationMode.Hight_Accuracy); // 设置定位模式
    androidOption.setScanspan(1000); // 设置发起定位请求时间间隔
    Map androidMap = androidOption.getMap();
    BaiduLocationIOSOption iosOption = new BaiduLocationIOSOption();
    Map iosdMap = iosOption.getMap();
    locationPlugin.requestPermission(); //请求定位权限
    locationPlugin.prepareLoc(androidMap,iosdMap); //ios和安卓定位设置
    locationPlugin.startLocation(); //开始定位
    //  获取定位结果
    var gps = locationPlugin.onResultCallback();
    gps.listen((event) {
      //print(event["address"]);     //错误信息
      AdressDet = event["address"];
      latitude=event["latitude"];
      longitude=event["longitude"];
      print('地址:'+AdressDet); //打印地址
      print('经纬度:$latitude+$longitude');
      Mycoordinate[0]=latitude ;
      Mycoordinate[1]=longitude;
      //print('状态码：'+event['locType'].toString());      //61为GPS定位成功,详情见官网文档
    });

    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  void didUpdateWidget(AdressHomePage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

//电话号码正则判断
  static bool isChinaPhoneLegal(String str) {
    return new RegExp(
        '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$')
        .hasMatch(str);
  }
  baibuGps() {
    LocationFlutterPlugin locationPlugin = new LocationFlutterPlugin();
    //创建一个定位对象，后续操作时使用
// 设置安卓定位参数(按官方文档复制过来就可以了)
    BaiduLocationAndroidOption androidOption = new BaiduLocationAndroidOption();
    androidOption.setCoorType("bd09ll"); // 设置返回的位置坐标系类型
    androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
    androidOption.setIsNeedAddres(true); // 设置是否需要返回地址信息
    androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
    androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
    androidOption.setOpenGps(true); // 设置是否需要使用gps
    androidOption.setLocationMode(LocationMode.Hight_Accuracy); // 设置定位模式
    androidOption.setScanspan(1000); // 设置发起定位请求时间间隔
    Map androidMap = androidOption.getMap();
    BaiduLocationIOSOption iosOption = new BaiduLocationIOSOption();
    Map iosdMap = iosOption.getMap();
    locationPlugin.requestPermission(); //请求定位权限
    locationPlugin.prepareLoc(androidMap,iosdMap); //ios和安卓定位设置
    locationPlugin.startLocation(); //开始定位
    //  获取定位结果
    var gps = locationPlugin.onResultCallback();
    gps.listen((event) {
      //print(event["address"]);     //错误信息
      AdressDet = event["address"];
      latitude=event["latitude"];
      longitude=event["longitude"];
      print('地址:'+AdressDet); //打印地址
      print('经纬度:$latitude+$longitude');
      Mycoordinate[0]=latitude;
      Mycoordinate[1]=longitude;
      //print('状态码：'+event['locType'].toString());      //61为GPS定位成功,详情见官网文档
    });
    // _locationPlugin.stopLocation();//停止定位
    return Mycoordinate;
  }
  getError() {
    return errorText;
  }
  void onBMFMapCreated(BMFMapController controller) {
    myMapController = controller;
    /// 地图加载回调
    myMapController?.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');
    });
  }

  Container generateMap(List coor) {
    return Container(
      height: 200,
      width: 400,
      child: BMFMapWidget(
        onBMFMapCreated: (controller) {
          onBMFMapCreated(controller);
            controller.setCenterCoordinate(BMFCoordinate(coor[0],coor[1]),false);    //点位改变
        },
        mapOptions: initMapOptions(),
      ),
    );
  }
}